package com.yun.zf.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.common.app.domain.SysCoupon;
import com.yun.zf.common.app.domain.SysCouponReceive;
import com.yun.zf.common.app.dto.center.MyCouponListDto;
import com.yun.zf.system.mapper.SysCouponReceiveMapper;
import com.yun.zf.system.service.SysCouponReceiveService;
import com.yun.zf.system.service.SysCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 优惠券领取记录表 服务实现类
 * </p>
 *
 * @author cj
 * @since 2021-05-31
 */
@Service
public class SysCouponReceiveServiceImpl extends ServiceImpl<SysCouponReceiveMapper, SysCouponReceive> implements SysCouponReceiveService {
    @Autowired
    private SysCouponService couponService;


    @Override
    public int receiveCoupon(SysCouponReceive couponReceive) {
        return baseMapper.insert(couponReceive);
    }

    /**
     * 获取我的优惠券列表
     * @param userId
     * @return
     */
    @Override
    public  Map<Integer, List<MyCouponListDto>> getCouponList(Long userId) {
        List<MyCouponListDto> couponListDtos = baseMapper.getUserCoupon(userId);
        if (couponListDtos.size()>0){
            Map<Integer, List<MyCouponListDto>> data =   couponListDtos.stream().collect(Collectors.groupingBy(MyCouponListDto::getUserStatus));

            return  data;
        }
        return null;
    }

    @Override
    public int receiveCoupon(String couponId, String userId) {
        //1 查询优惠券是否存在
     SysCoupon c = couponService.getCoupon(Long.parseLong(couponId));
     if (c==null){
         return  -1;
     }
     SysCouponReceive receive = new SysCouponReceive();
     receive.setCouponId(Long.parseLong(couponId));
     receive.setUserId(Long.parseLong(userId));
     receive.setCreateTime(new Date());
     // 优惠券使用时间
     if (c.getValidityType().equals("G")){
         receive.setRStartTime(c.getCStartTime());
         receive.setREndTime(c.getCEndTime());
     }else if (c.getValidityType().equals("F")){
         receive.setRStartTime(new Date());
         receive.setREndTime(DateUtil.offsetDay(new Date(),c.getLimitDay()));
     }
        return   baseMapper.insert(receive);
    }
}
